import UserManagerService from '@/api/userManager/api';

export default {
  namespace: 'userManagerModel',
  state: {
    dataSource: [],
    pagination: {
      current: 1,
      total: 1,
      pageSize: 10,
      showSizeChanger: true,
      pageSizeOptions: ['10', '50', '200', '500'],
    },
    userEditor: {
      isModalVisible: false,
      id: null,
    },
  },
  reducers: {
    setDataSource(state: any, { data }) {
      return {
        ...state,
        dataSource: data.dataSource,
        pagination: {
          ...state.pagination,
          current: data.current,
          pageSize: data.pageSize,
          total: data.total,
        },
      };
    },
    setUserEditor(state: any, { data }) {
      return {
        ...state,
        userEditor: data,
      };
    },
  },
  effects: {
    *queryUserList({ payload: data }, { call, put }) {
      const result = yield call(
        UserManagerService.queryUserList,
        data.queryParams,
        data.pageValue,
        data.pageSizeValue,
      );
      if (result) {
        yield put({ type: 'setDataSource', data: result });
      }
    },
    *initUserEditor({ payload: data }, { put }) {
      yield put({ type: 'setUserEditor', data: data });
    },
    *doCreateOrUpdateUser({ payload: data }, { call, put }) {
      const result = yield call(
        UserManagerService.doCreateOrUpdateUser,
        data.user,
      );
      if (result) {
        yield put({
          type: 'setUserEditor',
          data: {
            isModalVisible: false,
            id: null,
          },
        });
        data.resolve(true);
      }
    },
    *doDeleteUser({ payload: data }, { call }) {
      const result = yield call(UserManagerService.doDeleteUser, data.id);
      if (result) {
        data.resolve(true);
      }
    },
  },
};
